//
//  AppDelegate.m
//  Romomo
//
//  Created by puman on 16/9/30.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "AppDelegate.h"
#import "RMMRootViewController.h"
#import "RMMThridCommon.h"

@interface AppDelegate ()<WXApiDelegate, UIAlertViewDelegate>

@end

@implementation AppDelegate

- (void)dealloc{
    
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [[RMMRootViewController alloc] init];
    // 友盟统计
    [RMMThridCommon setUMTJ];
    // 搞得地图
    [RMMThridCommon setGaoDeMapKey];
    // 设置友盟分享
    [RMMThridCommon setUMShare];
    // 微信支付
    [WXApi registerApp:WXAPPID];
    [NSThread sleepForTimeInterval:1.0];
    [self.window makeKeyAndVisible];
    return YES;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
    }
    return [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NS_POST(@"PAYJIEGUOFUWU",[RMMFileManager shareHandle].payTypeName, resultDic);
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
        
    } else if ([url.host isEqualToString:@"pay"]){
        return [WXApi handleOpenURL:url delegate:self];
    } else {
        BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
        if (!result) {
        }
        return result;
    }
    return YES;
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NS_POST(@"PAYJIEGUOFUWU", [RMMFileManager shareHandle].payTypeName, resultDic);
            NSLog(@"result = %@",resultDic);
        }];
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    } else if ([url.host isEqualToString:@"pay"]){
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
-(void) onResp:(BaseResp*)resp{
    if ([resp isKindOfClass:[PayResp class]]){
        NSString *type = @"";
        switch (resp.errCode) {
            case WXSuccess:
                type = @"成功";
                break;
                
            default:
                type = @"失败";
                break;
        }
        NS_POST(@"PAYJIEGUOFUWU", [RMMFileManager shareHandle].payTypeName,@{@"type" : type} );
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)addAlertController{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"版本提示" message:@"亲爱的小主,有新版本了请您前往更新" delegate:self cancelButtonTitle:@"前往更新" otherButtonTitles:nil, nil];
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/cn/app/id994783305?mt=8"]];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // 程序将要进入前台
    NSString *app_Version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; // 项目版本号
    [OSRequestManager requestWithUrlString:GetVersionUrl parDic:nil method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSString *newVersion = [NSString stringWithFormat:@"%@",dataDic[@"data"]];
            if ([app_Version compare:newVersion] == NSOrderedAscending){
                [self addAlertController];
            }
        }
    } error:^(NSError *errors) {
        
    } view:self.window];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
